library(sf)
library(fs)
library(tidyverse)
library(ppmf)
library(redist)
library(geomander)
library(tigris)
library(here)

source("../00_custom_functions.R")

# Read in data ------
state <- "SC"
ppmf19 <- read_ppmf(state, "../../data-raw/ppmf_19.csv")
ppmf12 <- read_ppmf(state, "../../data-raw/ppmf_12.csv")
ppmf4 <- read_ppmf(state, "../../data-raw/ppmf_04.csv")

ppmf19 <- ppmf19 %>% add_geoid() %>% agg() %>% breakdown_geoid()
colnames(ppmf19) <- paste("v19", colnames(ppmf19), sep = "_")
ppmf19 <- ppmf19 %>% rename(GEOID = v19_GEOID)

ppmf12 <- ppmf12 %>% add_geoid() %>% agg() %>% breakdown_geoid()
colnames(ppmf12) <- paste("v12", colnames(ppmf12), sep = "_")
ppmf12 <- ppmf12 %>% rename(GEOID = v12_GEOID)

ppmf4 <- ppmf4 %>% add_geoid() %>% agg() %>% breakdown_geoid()
colnames(ppmf4) <- paste("v4", colnames(ppmf4), sep = "_")
ppmf4 <- ppmf4 %>% rename(GEOID = v4_GEOID)

vest_2018 <- st_read('../../data/SC/VEST/sc_2018/sc_2018.shp')

data(fips_codes)

# Merge Census blocks and PPMF ----
blk_census <- create_block_table(state = 'SC')

# Join PPMF and Census ----
blk_shp_SC <- blk_census %>%
    left_join(ppmf12, by = 'GEOID') %>%
    left_join(ppmf4, by = 'GEOID') %>% 
    left_join(ppmf19, by = "GEOID")

# Cleanup
# and remove duplicates
# and set missing block pop/vap to 0
# add block_group back (dropped by contains('.'))
blk_shp_SC <- blk_shp_SC %>% select(-contains('.'))
blk_shp_SC[is.na(blk_shp_SC)] <- 0
blk_shp_SC <- blk_shp_SC %>% breakdown_geoid()

blk_shp <- st_make_valid(blk_shp_SC)


# Cleanup VTDs and legislative districts ------
prec <- vest_2018 %>% st_transform(st_crs(blk_shp))

# Get Census Shapes from tigris
sld_low <- state_legislative_districts('SC', 'lower')
sld_up  <- state_legislative_districts('SC', 'upper')
cd      <- congressional_districts('SC')
vtd     <- voting_districts('SC')


# Align ppmf & precincts:
block_prec_match <- geo_match(from = blk_shp, to = prec, method = 'centroid')
block_vtd_match  <- geo_match(from = blk_shp, to = vtd, method = 'centroid')
vtd_low_match    <- geo_match(from = vtd, to = sld_low, method = 'area')
vtd_up_match     <- geo_match(from = vtd, to = sld_up, method = 'area')
vtd_cd_match     <- geo_match(from = vtd, to = cd, method = 'area')

vtd <- vtd %>% mutate(
    sld_low = sld_low$SLDLST[vtd_low_match],
    sld_up = sld_up$SLDUST[vtd_up_match],
    cd = cd$CD116FP[vtd_cd_match]
)

# assign
blk_shp$vtd <- block_vtd_match
ppmf_at_vtd <- ppmf_block2prec(blk_shp, vtd)


# Block to Precinct ------
# ppmf_at_prec <- ppmf_block2prec(ppmf_prec, precinct)

# join them together ----
sc <- vtd %>%
    mutate(vtd = row_number()) %>%
    left_join(ppmf_at_vtd, by = 'vtd')

sc$cd <- as.numeric(sc$cd)
sc$sld_lower <- as.numeric(sc$sld_low)
sc$sld_upper <- as.numeric(sc$sld_up)

sc_shp <- sc %>% mutate(row_id = row_number())


# project down elec ----
blk_shp$gov_vest_REP <- estimate_down(wts = blk_shp$vap, value = prec$G18GOVRMCM, group = block_prec_match)
blk_shp$gov_vest_DEM <- estimate_down(wts = blk_shp$vap, value = prec$G18GOVDSMI, group = block_prec_match)
blk_shp$gov_vest_OTH <- estimate_down(wts = blk_shp$vap, value = prec$G18GOVOWRI, group = block_prec_match)

# agg up elec ----
sc_shp$gov_vest_REP <- estimate_up(value = blk_shp$gov_vest_REP, group = block_vtd_match)
sc_shp$gov_vest_DEM <- estimate_up(value = blk_shp$gov_vest_DEM, group = block_vtd_match)
sc_shp$gov_vest_OTH <- estimate_up(value = blk_shp$gov_vest_OTH, group = block_vtd_match)

# Add county name
sc_cname <- filter(fips_codes, state == "SC") %>%
    mutate(County = str_to_upper(str_squish(str_remove(county, "County")))) %>%
    select(county_code, County) %>%
    deframe()
sc_shp$County <- sc_cname[sc_shp$COUNTYFP]

# reorder
sc_shp <- sc_shp %>%
    relocate(GEOID10, vtd, NAME10, cd, matches("sld_"), matches("County"))

# Save cleaned -----
write_rds(sc_shp, file = '../../data/SC/sc_shp.rds', compress = "xz")

# adj
sc_map_orig <- redist_map(sc_shp, existing_plan = cd, total_pop = pop)
sc_map_orig$adj %>% write_rds("../../data/SC/sc_adj.rds")


